<template>
  <div id="village">
    <div class="top">
      <img src="../../../assets/images/villagebg.jpg" />
      <div class="box">
        <p>请输入乡村名称</p>
        <el-input v-model="queryParams.villageName" placeholder="请输入乡村名称进行搜索" @keyup.enter.native="search">
          <el-button slot="append" icon="el-icon-search" @click="search"></el-button>
        </el-input>
        <div style="width: 300px; display: flex;align-items: center;justify-content: space-around;">
          <el-button @click="villageAdd" v-if="userRoles.indexOf('villageAdmin')==-1">新增乡村</el-button>
          <el-button @click="openImport" v-if="userRoles.indexOf('townshipAdmin')!=-1">导入数据</el-button>
        </div>
      </div>
    </div>
    <el-table v-loading="loading" :data="villageList">
      <el-table-column label="" align="center" prop="villageIntroduce" type="expand">
        <template slot-scope="scope">
          <div>乡村介绍：{{ scope.row.villageIntroduce }}</div>
        </template>
      </el-table-column>
      <el-table-column label="名称" align="center" prop="villageName" />
      <el-table-column label="联系人" align="center" prop="contactPerson">
        <template slot-scope="scope">
          {{ scope.row.contactPerson || "暂无联系人" }}
        </template>
      </el-table-column>
      <el-table-column label="联系电话" align="center" prop="contactNumber">
        <template slot-scope="scope">
          {{ scope.row.contactNumber || "暂无联系电话" }}
        </template>
      </el-table-column>
      <el-table-column label="等级" align="center" prop="villageGrade" :formatter="transtag" />
      <el-table-column label="图片数量" align="center" prop="villageImage">
        <template slot-scope="scope">
          <span>{{scope.row.villageImage.length}}</span>
        </template>
      </el-table-column>
      <el-table-column label="上传人" align="center" prop="userName">
        <template slot-scope="scope">
          {{ scope.row.userName || "暂无上传人" }}
        </template>
      </el-table-column>
      <el-table-column label="地址" align="center" prop="villageAddress" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">完善信息</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="padding-bottom: 40px;">
      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" />
    </div>

    <el-dialog title="数据导入" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="导入类型" prop="url">
          <el-select v-model="form.url" placeholder="请选择导入类型">
            <el-option v-for="(item,i) in importWay" :key="i" :label="item.type" :value="item.url" />
          </el-select>
        </el-form-item>
        <el-form-item label="导入数据" prop="batch" v-if="form.url">
          <el-upload class="upload-demo" :on-remove="fileRemove" :on-change="fileChange" :auto-upload="false"
            action="aa" :file-list="filelist" :accept="accept">
            <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
            <el-button style="margin-left: 10px;" size="small" type="text" @click="getTemplate">下载模板</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitImport" :loading="form.load">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { getVillageList, importWay, dataImport } from "@/api/route/townShipUpload";
  import Editor from "@/components/Editor";
  import ImageUpload from "@/components/ImageUpload";
  export default {
    name: "Shop_introduction",
    components: {
      Editor,
      ImageUpload,
    },
    data() {
      return {
        userRoles: [],
        importWay: importWay,
        accept: 'application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        // 遮罩层
        loading: true,
        // 总条数
        total: 0,
        //列表
        villageList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          villageName: ""
        },
        // 表单参数
        form: {
          load: false
        },
        filelist: [],
        // 表单校验
        rules: {
          url: [{ required: true, message: '请选择导入类型', trigger: 'change' }],
          batch: [{ required: true, message: '请上传导入数据', trigger: 'blur' }],
        },
        //等级字典
        levelOptions: [],
        //搜索框输入状态
        searchFlag: true,
        list: [],
      };
    },
    created() {
      this.userRoles = this.$store.state.user.roles;
      this.getList();
      this.getDicts("village_grade").then((response) => {
        this.levelOptions = response.data;
      });
    },
    methods: {
      getList() {
        this.loading = true;
        getVillageList(this.queryParams).then((response) => {
          const arr = response.rows.map(item => {
            item.villageImage = item.villageImage ? item.villageImage.split(",") : [];
            if (item.villageImage.length > 6) {
              item.villageImage = item.villageImage.slice(0, 5)
            }
            return item;
          });
          this.list = arr;
          this.total = response.total;
          this.villageList = arr;
          this.loading = false;
        });
      },
      transtag(row) {
        if (row.levelOptions) {
          return this.selectDictLabels(this.levelOptions, row.villageGrade);
        } else {
          return '暂无等级';
        }
      },

      //搜索框input事件
      search(e) {
        this.queryParams.pageNum = 1;
        this.getList()
      },

      //新增乡村按钮点击事件
      villageAdd() {
        this.$router.push("village_detail");
      },

      //完善信息按钮点击事件
      handleUpdate(row) {
        this.$router.push({ path: "village_detail", query: { id: row.id } });
      },

      openImport() {
        this.reset()
        this.open = true;
      },

      submitImport() {
        this.$refs['form'].validate(valid => {
          if (valid) {
            let param = new FormData(); //创建form对象
            param.append('file', this.form.file);
            this.form.load = true
            dataImport(this.form.url, param).then(res => {
              this.$message.success(res.msg)
              this.getList()
              this.cancel()
            }).catch(err => {
              this.form.load = false
            })
          }
        })
      },
      getTemplate() {
        window.location.href =
          "http://xyht.cnitcs.net/profile/upload/2023/excel/%E4%B9%A1%E6%9D%91%E4%BF%A1%E6%81%AF%E7%BB%9F%E8%AE%A1excel.rar"
      },
      fileRemove(file, fileList) {
        this.form.batch = null;
        this.form.file = null;
        this.$refs['form'].clearValidate(['batch']);
      },
      fileChange(file, fileList) {
        let status = true;
        if (fileList.length > 1 && file.status !== "fail") {
          fileList.splice(0, 1);
          status = false;
        } else if (file.status === "fail") {
          this.$message.error("上传失败，请重新上传！");
          fileList.splice(0, 1);
          status = false;
        }
        if (!this.accept.match(file.raw.type)) {
          this.$message.error("请上传excel文件!");
          fileList.splice(0, 1);
          status = false;
        }
        if (status) {
          this.$set(this.form, 'batch', file.name)
          this.$set(this.form, 'file', file.raw)
          this.$refs['form'].clearValidate(['batch']);
        }
      },
      reset() {
        this.form = {
          load: false
        };
        this.resetForm("form");
      },
      cancel() {
        this.reset()
        this.open = false;
      },
    },
  };
</script>
<style lang="scss" scoped>
  #village {
    overflow: hidden;

    .top {
      margin: 15px 30px;
      position: relative;

      img {
        width: 100%;

      }


      .box {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;

        p {
          color: #ffffff;
          font-size: 18px;
          font-weight: bold;
          margin: 0;

        }

        ::v-deep .el-input {
          width: 350px;
          margin: 1em 0;

          .el-input__inner {
            text-align: center;
          }

        }

        .el-button {
          height: 35px;
          background: #727375;
          color: #ffffff;
        }
      }


    }
  }
</style>